const mysql=require('mysql')

//链接到数据库文件

const conn = mysql.createConnection({
    host: "39.106.115.25",
    user: "bailian",
    password: "bailian",
    database: "bailian",
    port: 3306
})

//先链接数据库,看是否链接成功
conn.connect((err) => {                 //链接到数据库
    if (err) {
        console.log("连接失败了" + err.message)
        return
    }
    console.log('数据库连接成功')
})


//注册1
function exec(sql, params, callback) {

    //链接成功了就开始判断
    conn.query(sql, params, (err, result, fields) => {
        callback(err, result)             //都返回回去,在那边判断

        //释放连接
        // conn.destroy()
    })
}


//注册2
function execAsync(sql, params) {
    return new Promises((resolve, reject) => {

        //链接成功了就开始判断
        conn.query(sql, params, (err, result, fields) => {
            if (err) {
                reject(err, result, fields)
                throw err;
                return
            }

            resolve(err, result, fields)      //把正确答案返回出去
            //释放连接
            // conn.destroy()
        })
    })
}


module.exports = { exec, execAsync }